const db = uniCloud.database();
const dbCmd = db.command;
module.exports = {
	_before: function() { // 通用预处理器

	},

	async addSearch(user_id, content) {
		let a = await db.collection("search").where({
			user_id,
			content
		}).get();
		if (a.data.length==0) {
			let res = await db.collection("search").add({
				user_id,
				content,
				searchCount: 1,
				create_date: Date.now()
			})
		} else {
			let res = await db.collection("search").where({
				user_id,
				content
			}).update({
				searchCount: dbCmd.inc(1),
				create_date: Date.now()
			})
		}
	},

	//    async addSearchCount(content){
	//     let a=await db.collection("search").where({
	// 		content
	// 	}).get();
	// 	if(a.data){
	// 		let res=await db.collection("search").where({
	// 			content
	// 		}).update({
	// 			searchCount:dbCmd.inc(1)
	// 		});
	// 	}
	// },


	async Search(content) {
		let res = await db.collection("Snacks").where({
			name: new RegExp(content)
		}).get();
		return res;
	},

	async getSearchHistory(user_id) {
		let res = await db.collection("search").field({
			'content': true,
			'_id': false
		}).where({
			user_id
		}).orderBy("create_date", "desc").limit(10).get();
		return res;

	},

	async getSearchHot() {
		let res = await db.collection("search").groupBy('content').groupField('count(*) as total').get();
		return res;

	},


}